import {defineComponent, ref, h, DefineComponent, inject, nextTick,} from "vue";
import { NCard, NButton, NSpace, NButtonGroup,NSelect,NInputGroup, } from "naive-ui"
import Maincontainer from "@/components/maincontainer/index"
import Flexform, { flexformitem } from "@/components/flexform/index"
import useTableIndex from "@/hooks/tableindex"
import useHttpMessage from "@/hooks/oftenattr"
import useColums from "@/hooks/colums"
import Flextalbe from "@/components/flextable/index"
import Mypage from "@/components/mypage/index"


interface DateItem {
    year: number,       // 年
    month: number,  // 月
    day: number,    // 日
    week: number,   // 周
    weekzh: string, // 周，中文
    qiandao: Array<string>, // 要展示的数据
    timestamp: number,  //时间戳
    disabled: boolean,  // 非当前月份
    today: boolean, // 是否是今天
}

export default defineComponent({
    name: "Mykaoqin",
    setup() {
        const {
            formValue,
            loading,
            total,
            tableData,
            editRef,
            pageRef,
            formRef,
            handleSearch,
            handleResetForm,
            handleView,
            handleEdit,
            handleCreate,
            refreshDelete
        } = useTableIndex()
        const { http, message } = useHttpMessage()
        const yearOptions = ref<Array<{label:string,value:number}>>([])
        const monthOptions = ref([
            {label:"壹月",value:1},
            {label:"贰月",value:2},
            {label:"弎月",value:3},
            {label:"肆月",value:4},
            {label:"伍月",value:5},
            {label:"陆月",value:6},
            {label:"柒月",value:7},
            {label:"捌月",value:8},
            {label:"玖月",value:9},
            {label:"拾月",value:10},
            {label:"拾壹月",value:11},
            {label:"拾贰月",value:12},
        ])
        const pushyear = ()=>{
            if(yearOptions.value.length > 0 )return
            for(let i=0;i<=200;i++){
                yearOptions.value.push({label:`${1900+i}年`,value:1900+i})
            }
        }
        // 自定义属性区域
        const donghua = ref("")
        const overDeleteFunc: Function | undefined = inject("overDeleteFunc")
        const handleDelete = (data: any, index: number) => {
            const params = { "id": data.id }
            overDeleteFunc && overDeleteFunc(params, http.zidiandelete, refreshDelete, "字典")
        }
        const valueRef = ref<DefineComponent | null>(null)
        const formList = ref([
            {
                span: 6,
                label: "名称",
                key: "name",
                default: "",
                type: "input",
                placeholder: "请输入名称",
            },
            { slot: (item: flexformitem) => <div class="w-full"></div>, span: 6, type: "slot" },
            { slot: (item: flexformitem) => <div class="w-full"></div>, span: 6, type: "slot" },
            {
                slot: (item: flexformitem) => <div class="w-full mt-3px">
                    <NButton size={"small"} onClick={handleSearch}>搜索</NButton><NButton size={"small"} onClick={handleResetForm}>重置</NButton><NButton size={"small"} onClick={handleCreate}>新建</NButton></div>, span: 6, type: "slot"
            }
        ])
        const { index, createdTime, changeTime, desc, name, } = useColums()
        const showDictValue = (data: any, index: number) => {
            console.log("点击查看", index, editRef.value);
            valueRef.value && valueRef.value.handleInit(data)
        }
        const colnums = ref([
            index,
            name,
            desc,
            createdTime,
            changeTime,
            {
                title: "字典值",
                width: 100,
                render: (data: any, index: number) => {
                    return h(NSpace, {}, {
                        default() {
                            return [
                                h(NButton, { size: "small", onClick: () => showDictValue(data, index), text: true, type: "info" }, { default() { return "字典值" } }),
                            ]
                        }
                    })
                }
            },
            {
                title: "操作",
                width: 200,
                render: (data: any, index: number) => {
                    return h(NSpace, {}, {
                        default() {
                            return [
                                h(NButton, { size: "small", onClick: () => handleView(data), type: "primary" }, { default() { return "查看" } }),
                                h(NButton, { size: "small", onClick: () => handleEdit(data), type: "info" }, { default() { return "修改" } }),
                                h(NButton, { size: "small", onClick: () => handleDelete(data, index), type: "error" }, { default() { return "删除" } }),
                            ]
                        }
                    })
                }
            },
        ])

        const getTableDataFunc = (page: number, pageSize: number) => {
            const params = { page, pageSize, ...formValue.value }
            http.zidianlist(params).then((res: any) => {
                if (res.data.code === 0) {
                    tableData.value = res.data.items
                    total.value = res.data.total
                } else {
                    message.error(res.msg || "获取字典数据列表失败")
                }
            }).catch((err: Error) => {
                message.error(err.message || "系统错误");
            })
        }
        const hanzimap: { [key: string]: string } = {
            "1": "周一",
            "2": "周二",
            "3": "周三",
            "4": "周四",
            "5": "周五",
            "6": "周六",
            "0": "周日",
        }
        const hanzimap2: { [key: string]: string } = {
            "0": "零",
            "1": "壹",
            "2": "贰",
            "3": "弎",
            "4": "肆",
            "5": "伍",
            "6": "陆",
            "7": "柒",
            "8": "捌",
            "9": "玖",
            "10": "拾",
            "11": "拾壹",
            "12": "拾贰",
        }
        // 数字转汉字
        const weektozh = (week: number): string => {
            return hanzimap[week.toString()] || ""
        }
        const monthtozh = (month: number): string => {
            return hanzimap2[month.toString()] || ""
        }
        // 时间列表
        const daylist = ref<Array<DateItem>>([])
        // 今天的日期
        const nowtime = ref<{ year: number, month: number, day: number }>({
            year: 0,
            month: 0,
            day: 0,
        })
        // 当前的日期
        const thisdate = ref<{ year: number, month: number, day: number }>({
            year: 0,
            month: 0,
            day: 0,
        })
        // 计算需要展示的第一个日期
        const getfirstday = (shijian: Date): number => {
            console.log("cloneNowDate", shijian);
            // 先获取这个月的第一天
            shijian.setDate(1)
            console.log("cloneNowDate", shijian);
            // 获取第一天是周几  ，修改2021年7月26日 14:42:58，周日是0不是7，我草。
            let firstdayweek = new Date(shijian).getDay()
            if (firstdayweek === 0) {
                firstdayweek = 7
            }
            // 展示时间的第一天
            return shijian.getTime() - (firstdayweek - 1) * 24 * 60 * 60 * 1000
        }

        const pushdatetolist = (shijian: Date) => {
            daylist.value = []
            const firstday = getfirstday(shijian)
            console.log("firstday", new Date(firstday));
            for (let i = 0; i <= 60; i++) {
                let shuju: DateItem = {
                    year: 0,
                    month: 0,
                    day: 0,
                    week: 0,
                    weekzh: "",
                    qiandao: [],
                    timestamp: 0,
                    disabled: false,
                    today: false,
                }
                const shijianchuo = firstday + i * 24 * 60 * 60 * 1000
                const sj = new Date(shijianchuo)
                const nian1 = sj.getFullYear()
                const yue1 = sj.getMonth() + 1
                const ri1 = sj.getDate()
                const week = sj.getDay()
                if (thisdate.value.month === 1) {
                    if (yue1 > thisdate.value.month && yue1 !== 12) {
                        if (week === 1 || week === 7) { break }
                    }
                } else if (thisdate.value.month === 12) {
                    if (yue1 - thisdate.value.month === -11) {
                        if (week === 1 || week === 7) { break }
                    }
                } else {
                    if (yue1 > thisdate.value.month) {
                        if (week === 1 || week === 7) { break }
                    }
                }
                shuju["timestamp"] = shijianchuo
                shuju["year"] = nian1
                shuju["month"] = yue1
                shuju["day"] = ri1
                shuju["week"] = week
                shuju["weekzh"] = weektozh(week)
                shuju["disabled"] = yue1 !== thisdate.value.month
                shuju["today"] = nian1 === nowtime.value.year && yue1 === nowtime.value.month && ri1 === nowtime.value.day
                daylist.value.push(shuju)
            }
        }
        // 点击上个月
        const shanggeyue = () => {
            thisdate.value.month = thisdate.value.month - 1
            if (thisdate.value.month <= 0) {
                thisdate.value.year = thisdate.value.year - 1
                thisdate.value.month = 12
            }
            pushdatetolist(new Date(thisdate.value.year, thisdate.value.month - 1, thisdate.value.day))
        }
        // 点击下个月
        const xiageyue = () => {
            thisdate.value.month = thisdate.value.month + 1
            if (thisdate.value.month > 12) {
                thisdate.value.year = thisdate.value.year + 1
                thisdate.value.month = 1
            }
            pushdatetolist(new Date(thisdate.value.year, thisdate.value.month - 1, thisdate.value.day))
        }
        // 点击回到今天
        const gototoday = () => {
            if (thisdate.value.year !== nowtime.value.year || thisdate.value.month !== nowtime.value.month || thisdate.value.day !== nowtime.value.day) {
                thisdate.value.year = nowtime.value.year
                thisdate.value.month = nowtime.value.month
                thisdate.value.day = nowtime.value.day
                pushdatetolist(new Date(thisdate.value.year, thisdate.value.month - 1, thisdate.value.day))
            }
            // 增加一个闪烁的函数
            donghua.value = "transform transition-all duration-1000 bg-red-400 shanshuo"
            setTimeout(()=>{
                donghua.value = ""
            },2000)
        }
        // 修改年月的回调
        const changeDate=()=>{
            nextTick(()=>{
                pushdatetolist(new Date(thisdate.value.year, thisdate.value.month - 1, thisdate.value.day))
            })
        }
        // 初始化函数
        const init = () => {
            // 初始化的时候，填充年份
            pushyear()
            const xianzai = new Date()
            nowtime.value.year = thisdate.value.year = xianzai.getFullYear()
            nowtime.value.month = thisdate.value.month = xianzai.getMonth() + 1
            nowtime.value.day = thisdate.value.day = xianzai.getDate()
            pushdatetolist(xianzai)
        }
        init()
        return () => (
            <Maincontainer class="bg-white">
                <div class="w-full h-10 flex justify-between items-center "> 
                    <NInputGroup class="w-auto">
                        <NSelect v-slots={{arrow: ()=>{}}} v-model={[thisdate.value.year,"value"]} options={yearOptions.value} onUpdateValue={changeDate} class="w-100px" />
                        <NSelect v-slots={{arrow: ()=>{}}} v-model={[thisdate.value.month,"value"]} options={monthOptions.value} onUpdateValue={changeDate} class="w-100px" />
                    </NInputGroup>
                    <NButtonGroup>
                        <NButton round={true} type={"primary"} ghost={true} onClick={shanggeyue}>上个月</NButton>
                        <NButton round={true} type={"primary"} ghost={true} onClick={xiageyue}>下个月</NButton>
                    </NButtonGroup>
                    <NButtonGroup>
                        <NButton type={"info"} ghost={true} onClick={gototoday}>回到今天</NButton>
                    </NButtonGroup>
                </div>
                <div class="w-full flex-1 flex flex-wrap content-start border border-gray-300">
                    {() => daylist.value.map(item => {
                        return <div class={["w-1/7 h-20 flex flex-col border border-gray-300 p-1 ", item.disabled ? " text-gray-200" : " text-black",item.today ? donghua.value : ""]}>
                            <div class="w-full flex justify-between items-center">
                                <span>{item.day}</span>
                                <span class="text-green-400">{item.today ? "今天" : ""}</span>
                                <span>{item.weekzh}</span>
                            </div>
                            <div class="w-full flex-1 overflow-y-auto">
                                {() => item.qiandao.map(qiandaoitem => {
                                    return <span>{qiandaoitem}</span>
                                })}
                            </div>
                        </div>
                    })}
                </div>
            </Maincontainer>
        )
    },
})
